home *** CD-ROM | disk | FTP | other *** search
/ Nebula 2 / Nebula Two.iso / NextAnswers / 1893_Building_SATAN_for_NEXTSTEP.rtfd / putenv.c next >
C/C++ Source or Header  |  1995-04-07  |  1KB  |  73 lines

  1. extern int putenv(char *newval)
  2. {
  3.     extern char **environ;
  4.  
  5.     static int firstTime = 1;
  6.     char **ep;
  7.     char *cp;
  8.     int esiz;
  9.     char *np;
  10.  
  11.     if (!(np = strchr(newval, '=')))
  12.     return 1;
  13.     *np = '\0';
  14.  
  15.     /* look it up */
  16.     for (ep=environ ; *ep ; ep++)
  17.     {
  18.     /* this should always be true... */
  19.     if (cp = strchr(*ep, '='))
  20.     {
  21.         *cp = '\0';
  22.         if (!strcmp(*ep, newval))
  23.         {
  24.         /* got it! */
  25.         *cp = '=';
  26.         break;
  27.         }
  28.         *cp = '=';
  29.     }
  30.     else
  31.     {
  32.         *np = '=';
  33.         return 1;
  34.     }
  35.     }
  36.  
  37.     *np = '=';
  38.     if (*ep)
  39.     {
  40.     /* the string was already there: just replace it with the new one */
  41.     *ep = newval;
  42.     return 0;
  43.     }
  44.  
  45.     /* expand environ by one */
  46.     for (esiz=2, ep=environ ; *ep ; ep++)
  47.     esiz++;
  48.     if (firstTime)
  49.     {
  50.     char **epp;
  51.     char **newenv;
  52.     if (!(newenv = malloc(esiz * sizeof(char *))))
  53.         return 1;
  54.    
  55.     for (ep=environ, epp=newenv ; *ep ;)
  56.         *epp++ = *ep++;
  57.     *epp++ = newval;
  58.     *epp = (char *) 0;
  59.     environ = newenv;
  60.     }
  61.     else
  62.     {
  63.     if (!(environ = realloc(environ, esiz * sizeof(char *))))
  64.         return 1;
  65.     environ[esiz - 2] = newval;
  66.     environ[esiz - 1] = (char *) 0;
  67.     firstTime = 0;
  68.     }
  69.  
  70.     return 0;
  71. }
  72.  
  73.